package org.easy.tool.common;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReader;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Valley
 * Created by Valley on 2023/10/10 15:59
 */
public class CsvUtil {

    /**
     * 功能：读取CSV文件数据,参数为csv文件路径
     */
    public static List<List<Object>> readData(String path) throws Exception{
        CsvData data = csvData(path);
        return data.getRows().stream()
                .map(row->row.getRawList().stream()
                        .map(str->(Object) str)
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());
    }

    /**
     * 功能：读取文件头
     */
    public static List<String> readHeader(String path) throws Exception{
        CsvData data = csvData(path);
        return data.getHeader();
    }

    /**
     * 功能：读取CSV文件数据,参数为csv文件路径，获取CsvData
     */
    private static CsvData csvData(String path) throws Exception{
        CsvReader reader = reader();
        CsvData data = reader.read(FileIOUtil.file(path));
        reader.close();
        return data;
    }

    /**
     * 功能：获取CSV默认reader对象
     */
    private static CsvReader reader() {
        return cn.hutool.core.text.csv.CsvUtil.getReader();
    }

}
